import sys
import getopt
from libVirgil import ddithreecodecategories as ddi31CC
from libVirgil import converter as converter
import argparse

VERSION = '0.0.1'
REVISION = "$Revision: 12 $"

#Nifty little class to make dict()s accessible by javascript dot notation
#From here: http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/
class Bunch(dict):
    def __init__(self,**kw):
        dict.__init__(self,kw)
        self.__dict__ = self

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:],
                    "hi:c:C:s:o:O:d:",
                    ["help","infile=","code=","category=","sep=","outfile=","outputType=","ddiID=","codeSchemeID=","categorySchemeID="]
                )
        except getopt.error, msg:
             raise Usage(msg)
        # more code, unchanged

        # process options
        sep             = ","
        header          = True
        infile          = None
        outfile         = None
        outtype         = converter.outputTypes.DDI31
        codetype        = converter.codeTypes.Referential
        categorytype    = converter.categoryTypes.PrefixEmbedded
        defaultLanguage = 'en'
        ddiID           = None

        for o, a in opts:
            if o in ("-h", "--help"):
                print __doc__
                sys.exit(0)
            elif o in ("-i", "--infile"):
                infile = a
            elif o in ("-c","--code"):
                codetype = converter.codeTypes[a]
            elif o in ("-C","--category"):
                categorytype = converter.categoryTypes[a]
            elif o in ("-o","--outfile"):
                outfile = a
            elif o in ("-d","--ddiID"):
                ddiID = a
            elif o in ("--codeSchemeID"):
                codeSchemeID = a
            elif o in ("--categorySchemeID"):
                categorySchemeID = a
        # process arguments
        for arg in args:
            pass
        
        con = converter.converter(file=infile, header=header, sep=sep, defaultLanguage=defaultLanguage,
                             codetype=codetype, categorytype=categorytype, output=outtype)

        # check which output format we need
        output = None
        if con.outputtype == converter.outputTypes.DDI31:
            output = ddi31CC.ddi_CC_wrapper(id=ddiID)
        output.newCategoryScheme(categorySchemeID)
        output.newCodeScheme(codeSchemeID)

        code_id_prepend = codeSchemeID
        category_id_prepend = categorySchemeID
        for classn in con.convert():
            classn['code_id']     = "%s__%s"%(code_id_prepend,classn['code'])
            classn['category_id'] = "%s__%s"%(category_id_prepend,classn['code'])
            if classn['parent'] is not None:
                classn['parent']  = "%s__%s"%(code_id_prepend,classn['parent'])
            output.newClassification(classn,codeSchemeID,categorySchemeID)
            print classn['code'], classn['parent']     

        if outfile is None:
            print output.toString()
        else:
            print "sdfsdf"
            with open(outfile,'w') as f:
                print "sdfsdf"
                f.write(output.toString())
            print "sdfsdf"

    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2

if __name__ == "__main__":
    sys.exit(main())
